const Device = require('../models/Device');
const mqtt = require('mqtt');
const client = mqtt.connect(require('../config/mqtt.config').broker);

exports.getDevices = async (req, res) => {
  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 10;

  const devices = await Device.findAndCountAll({
    where: { user_id: req.user.id },
    offset: (page - 1) * limit,
    limit: limit,
    include: [{ model: DeviceGroup }]
  });

  res.json({
    data: devices.rows,
    pagination: {
      page,
      total: devices.count,
      pages: Math.ceil(devices.count / limit)
    }
  });
};

exports.addDevice = async (req, res) => {
  const { name, type, groupId } = req.body;

  try {
    const device = await Device.create({
      user_id: req.user.id,
      group_id: groupId,
      device_name: name,
      device_type: type,
      status: {}
    });
    res.status(201).json(device);
  } catch (error) {
    res.status(400).json({ error: '添加设备失败' });
  }
};

exports.deleteDevice = async (req, res) => {
  const device = await Device.findByPk(req.params.id);

  if (!device || device.user_id !== req.user.id) {
    return res.status(403).json({ error: '无权操作' });
  }

  await device.destroy();
  res.json({ success: true });
};

exports.updateDeviceState = async (req, res) => {
  const device = await Device.findByPk(req.params.id);

  if (!device || device.user_id !== req.user.id) {
    return res.status(403).json({ error: '无权操作' });
  }

  const { action, params } = req.body;
  client.publish(`device/${device.id}/cmd`, JSON.stringify({ action, params }));

  res.json({ success: true });
};